package com.test.netty.nettyhb;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Calendar;

@Slf4j
public class MessageHandler extends SimpleChannelInboundHandler<CProtocol.Message> {

    private int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CProtocol.Message msg) throws Exception {
        readIdleTimes = 0;
        switch (msg.getType()) {
            case HEARTBEAT:
                log.info(" ====== > [MessageHandler] HEARTBEAT received : " + msg.getTypeValue());
                CProtocol.Message message = ProtobufUtils.createMessage(CProtocol.Heartbeat.newBuilder().build());
                ctx.channel().writeAndFlush(message);
                break;
            case REQUEST:
                log.info(" 其他信息处理 ... ");
                ctx.fireChannelRead(msg);
                break;
            default:
                break;
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        String eventType = null;
        switch (event.state()) {
            case READER_IDLE: // 读空闲的计数加1
                eventType = "读空闲";
                readIdleTimes++;
                String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
                log.info(String.format("READER IDLE Time:[%s], TIMES:[%s]", now, readIdleTimes));
                break;
            case WRITER_IDLE: // 写空闲 不处理
                eventType = "写空闲";
                break;
            case ALL_IDLE: // 读写空闲 不处理
            default:
                eventType = "读写空闲";
                break;
        }
//        log.info(ctx.channel().remoteAddress() + "超时事件：" + eventType);
//        log.info("====>readIdleTimes:" + readIdleTimes);
        if (readIdleTimes > 3) {
            log.info(" [server]读空闲超过3次，关闭连接");
            ctx.channel().writeAndFlush("you are out");
            ctx.channel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
